<template>
  <div>
  <el-dialog
    title="新增任务"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    width="720px"
    v-dialog-drag
    :close-on-click-modal="false"
    top="5vh"
    @close="handleClose()"
    @open="handleOpen()"
  >
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="所属工厂" prop="branchcodeName">
        <el-input type="text" v-model="form.branchcodeName" disabled placeholder="请选择所属工厂"></el-input>
      </el-form-item>

      <el-form-item label="所属车间" prop="workshopId">
        <el-select
          v-model="form.workshopId"
          placeholder="请选择车间"
          clearable
          size="small"
          @change="handleWorkshop"
        >
          <el-option
            v-for="item in workshopList"
            :key="item.workshopId"
            :label="item.workshopName"
            :value="item.workshopId"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属产线" prop="lineId">
        <el-select
          v-model="form.lineId"
          placeholder="请选择产线"
          clearable
          size="small"
          @change="handleLine"
        >
          <el-option
            v-for="item in lineList"
            :key="item.lineId"
            :label="item.lineName"
            :value="item.lineId"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="关联改善点" prop="pointName">
        <el-input type="text" v-model="pointName" placeholder="请选择关联改善点" readonly :disabled='!!pointId'>
          <el-button slot="append" icon="el-icon-search" @click="openPointDialog" readonly :disabled='!!pointId'></el-button>
        </el-input>
      </el-form-item>

      <el-form-item label="执行人" prop="execName">
        <el-input type="text" v-model="form.execName" placeholder="请选择执行人" readonly>
          <el-button slot="append" icon="el-icon-search" @click="openUserDialog"></el-button>
        </el-input>
      </el-form-item>

      <el-form-item label='执行时间' prop="handleDate">
        <el-date-picker
          clearable
          size="small"
          v-model="form.handleDate"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="-"
          start-placeholder="请选择开始时间"
          end-placeholder="请选择结束时间"
          @change="handleChangeDate">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="任务名称" prop="taskName">
        <el-input type="text" v-model="form.taskName" placeholder="请输入任务名称"></el-input>
      </el-form-item>

      <el-form-item label="任务内容" prop="taskDes">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2}"
          maxlength="200"
          show-word-limit
          placeholder="请输入任务内容"
          v-model="form.taskDes">
        </el-input>
      </el-form-item>

      <el-form-item label="附件">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :headers="{Authorization:token}"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-upload='beforeAvatarUpload'
          :on-success='handleSuccess'
          :accept="acceptFile"
          multiple
          :limit="10"
          :on-exceed="handleExceed"
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">请上传大小不超过 5MB 格式为 jpg/png/gif/pdf/doc/docx/xls/xlsx/ppt/pptx/jpeg/zip 的文件，最多10个。</div>
        </el-upload>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" :loading="saveloading" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
    <userList
      :visibles.sync="userDialog.visible"
      :multiple="false"
      :defaultValues="userDialog.defaulSelectUsers"
      :branchinnercode="userDialog.branchinnercode"
      @closeDialog="closeUserDialog"
    ></userList>

    <pointList
      :visibles.sync="pointDialog.visible"
      :multiple="false"
      :defaultValues="pointDialog.defaulSelectUsers"
      @closeDialog="closePointDialog"
    />
  </div>
</template>
<script>
  import { getToken } from '@/utils/auth'
  import { fileTypes } from '@/utils/file'
  import service from "../../../utils/request";
  import { GEN_SERVER } from '@/config/baseUrl'
  import pointList from "./pointList";
  import {taskCreate,taskAddOrUpdate} from "@/api/leanTask/report";
  import {mapGetters} from "vuex";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default: ()=>{}
    }
  },
  data() {
    return {
      form: {
        factoryDeptCode:null,
        factoryDeptId:null,
        workshopId:null,
        lineId:null,
        branchcodeName:null,
        taskName:null,
        taskDes:null,
        execName:null,
        execUserName:null,
        handleDate:null,
        execStartDate:null,
        execEndDate:null,
        id:null,
        fileIds:[]
      },
      fileTypes,
      fileList:[],
      workshopList:[],
      lineList:[],
      rules: {
        branchcodeName: [
          { required: true, message: "请选择所属工厂", trigger: "change" },
        ],
        execName: [
          { required: true, message: "请选择执行人", trigger: "change" }
        ],
        handleDate:[
          { required: true, message: "请选择执行时间", trigger: "change" }
        ],
        taskName: [
          { required: true, message: "请输入任务名称", trigger: ['blur','change'] },
          { max: 30, message: "任务名称不能超过32个字符", trigger: ['blur','change'] }
        ],
        taskDes: [
          { required: true, message: "请输入任务内容", trigger: ['blur','change'] },
          { max: 200, message: "任务内容不能超过200个字符", trigger: ['blur','change'] }
        ]
      },
      userDialog: {
        visible: false,
        defaulSelectUsers:[],
        branchinnercode:null
      },
      pointDialog: {
        visible: false,
        defaulSelectUsers:[]
      },
      pointId:null,
      pointName:null,
      saveloading: false
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val)
      },
      get() {
        return this.visible
      }
    },
    ...mapGetters([
      'baseDeptId',
      'baseDeptName',
      'baseDeptCode',
      'allList'
    ]),
    uploadUrl(){
      return service.baseURL + GEN_SERVER['form-server'] + '/refine/report/upload'
    },
    token() {
      return 'Bearer ' + getToken()
    },
    acceptFile(){
      return Object.values(this.fileTypes).join(",")
    }
  },
  methods: {
    handleClose() {
      this.saveloading = false
      this.resetFormData()
    },

    handleOpen() {
      const result = this.getOwnFirstLine()
      this.resetFormData();
      if(this.row){//改善点审核通过，创建任务
        this.form.taskName = this.row.reportTaskName;
        this.form.taskDes = this.row.reportTaskDes;
        this.form.id = this.row.id;
        this.pointId = this.row.id;
        this.pointName = this.row.reportTaskName;
        this.form.workshopId = this.row.workshopId;
        this.form.lineId = this.row.lineId;
      }
      this.form.branchcodeName = this.baseDeptName;
      this.form.factoryDeptCode = this.baseDeptCode;
      this.form.factoryDeptId = this.baseDeptId;
      
      this.form.workshopId = this.form?.workshopId ? this.form?.workshopId : result[1]?.workshopId;
      this.form.lineId = this.form?.lineId ? this.form?.lineId : result[2]?.lineId;
      if(this.form.factoryDeptId){
        const factoryItem = this.allList.find(ele => ele.factoryDeptCode === this.form.factoryDeptCode);
        this.workshopList = factoryItem?.workshopVos ? factoryItem?.workshopVos : [];
      }
      if(this.form.workshopId){
        this.handleWorkshop(this.form.workshopId,"init")
      }
    },

    handleSubmit() {
      this.saveloading = true
      this.$refs.ruleForm
      .validate((flag) => {
        if (flag) {
          const parmas = {
            factoryDeptCode:this.form.factoryDeptCode,
            factoryDeptId:this.form.factoryDeptId,
            workshopId:this.form.workshopId,
            lineId:this.form.lineId,
            taskName:this.form.taskName,
            taskDes:this.form.taskDes,
            execUserName:this.form.execUserName,
            execStartDate:this.form.execStartDate,
            execEndDate:this.form.execEndDate,
            fileIds:this.form.fileIds
          }
          let postUrl = taskCreate;
          if(this.form.id){//关联改善点
            postUrl = taskCreate;
            parmas.id = this.form.id
          }else{//没有关联改善点
            postUrl = taskAddOrUpdate
          }
          postUrl(parmas).then(res => {
            if (res.code == 200) {
              this.msgSuccess("操作成功")
              this.$emit("submit-success")
              this.dialogVisible = false
            } else {
              this.msgError(res.msg || "操作失败")
            }
            this.saveloading = false
          }).catch(() => {
            this.msgError("操作失败")
            this.saveloading = false
          })
        } else {
          this.saveloading = false
        }
      })
    },

    //打开人员选择器
    openUserDialog() {
      this.userDialog.defaulSelectUsers = [];
      this.userDialog.branchinnercode = this.baseDeptId;
      if(this.form.execUserName){
        this.userDialog.defaulSelectUsers.push({
          username:this.form.execUserName,
          realname:this.form.execName
        })
      }
      this.userDialog.visible = true
    },

    closeUserDialog(list){
      if(list?.length){
        this.form.execUserName = list.map(item => item.username).join();
        this.form.execName = list.map(item => item.realname).join()
      }else{
        this.form.execUserName = null;
        this.form.execName = null;
      }
    },

    //打开改善点选择器
    openPointDialog() {
      this.pointDialog.defaulSelectUsers = [];
      if(this.form.id){
        this.pointDialog.defaulSelectUsers.push({
          id:this.form.id,
          reportTaskName:this.pointName
        })
      }
      this.pointDialog.visible = true
    },

    closePointDialog(list){
      if(list?.length){
        this.form.id = list.map(item => item.id).join();
        this.pointName = list.map(item => item.reportTaskName).join()
        this.form.taskName = list[0].reportTaskName;
        this.form.taskDes = list[0].reportTaskDes;
        // this.$refs.ruleForm?.validateField(["taskName","taskDes"])
      }else{
        this.form.id = null;
        this.pointName = null;
        this.form.taskName = null;
        this.form.taskDes = null;
      }
    },

    //选择车间,获取产线数据
    handleWorkshop(val,key){
      const workshopItem = this.workshopList.find(ele => ele.workshopId === val);
      this.lineList = workshopItem?.productionLineVos ? workshopItem?.productionLineVos : [];
      if(key != "init"){
        this.form.lineId = null;
      }
    },

    handleLine(val){
      this.form.lineId = val;
      this.$forceUpdate()
    },

    handleChangeDate(item){
      if (item) {
        this.form.execStartDate = item[0];
        this.form.execEndDate = item[1];
      } else {
        this.form.execStartDate = "";
        this.form.execEndDate = "";
      }
    },

    handleSuccess(response, file, fileList){
      this.fileList = fileList;
      this.form.fileIds = fileList.map(ele => ele.response?.data)
    },

    handleRemove(file, fileList) {
      this.fileList = fileList;
      if(fileList?.length){
        this.form.fileIds = fileList.map(ele => ele.response?.data)
      }else{
        this.form.fileIds = []
      }
    },

    getObjectURL(file) {
      var url = null;
      if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file);
      } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    },

    handlePreview(file) {
      var previewUrl = this.getObjectURL(file.raw);
      window.open(previewUrl)
    },

    beforeAvatarUpload(file){
      if(!this.acceptFile.includes(file.type)){
        this.msgWarning("暂不支持上传该格式文件");
        return false
      }
      if(file.size / 1024 / 1024  > 5){
        this.msgWarning("上传的附件大小不得超过5M");
        return false
      }
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 10个文件，本次选择了 ${files.length} 个文件`);
      return false
    },

    resetFormData() {
      this.$refs.ruleForm?.resetFields()
      this.form = {
        factoryDeptCode:null,
        branchcodeName:null,
        taskName:null,
        taskDes:null,
        execName:null,
        execUserName:null,
        handleDate:null,
        execStartDate:null,
        execEndDate:null,
        fileIds:[]
      };
      this.fileList = [];
      this.pointId = null;
      this.pointName = null;
    },
  },
  components:{
    pointList
  }
};
</script>
<style lang="scss" scoped>
.el-form {
  .el-date-editor.el-input,
  .el-range-editor,
  .el-select {
    width: 100%;
  }
}
.tool-bar{
  margin-bottom:20px
}
</style>
